import { login } from '@a/login.js'
import { getMenuList } from '@/api/menu.js'
import { getAllDepts } from '@/api/dept.js'
// import { menuList111 } from '@/store/menu.js'
import { getDistinctList } from '@a/core/user.js'
import { getLogisticsList } from '@a/business/site.js'

import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

// console.log(menuList111)
function changeDeptList2Tree(parentId, list) {
  // 过滤出parentId是一样的部门
  const array = list.filter(dept => {
    return dept.parentId === parentId
  })
  array.forEach(element => {
    const children = changeDeptList2Tree(element.id, list)
    if (children && children.length >= 1) {
      element.children = children // element.children为级联选择器中的children
    }
  })
  return array
}

const state = {
  token: getToken(),
  hasToken: '',
  menuList: [],
  // userInfo: {}, // 用户信息(测试)
  deptList: [],
  areaList: [], // 区域树形
  logisticsList: [], // 物流公司
  oriDeptList: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
    state.hasToken = token
  },
  SET_MENULIST: (state, menuList) => {
    state.menuList = menuList
  },
  SET_AREALIST: (state, areaList) => {
    state.areaList = areaList
  },
  SET_LOGISTICSLIST: (state, logisticsList) => {
    state.logisticsList = logisticsList
  }
  // SET_USERINFO: (state, userInfo) => {
  //   state.userInfo = userInfo
  // }
}

const actions = {
  // 获取用户所带token信息
  login({ commit }, data) {
    // console.log(data)
    return new Promise((resolve, reject) => {
      login(data).then(response => {
        if (response.code === 0) {
          // console.log(response)
          commit('SET_TOKEN', response.data.accessToken)
          // commit('SET_USERINFO', response.data)
          localStorage.setItem('userInfo', JSON.stringify(response.data))
          setToken(response.data.accessToken) // 登录成功后把token给到Cookies
          resolve()
        } else {
          reject(response.msg)
        }
      })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 获取菜单 && 获取菜单里面对应的权限(增删改查按钮)  有接口的情况下
  getMenuList111({ commit, state }) {
    return new Promise((resolve, reject) => {
      const { id } = state.userInfo
      getMenuList(id).then(response => {
        if (response.code === 200) {
          const menuList = response.list // 该用户拥有的所有路由权限和permisson按钮权限
          if (!menuList) {
            reject(response.msg)
          }
          commit('SET_MENULIST', menuList)
          resolve({ menuList })
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  getMenuList({ commit, state }) {
    // console.log(1)
    return new Promise((resolve, reject) => {
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      // console.log(userInfo.userId)
      const userId = userInfo.userId
      getMenuList('', userId).then(response => {
        // console.log(response)
        if (response.code === 0) {
          // var aaa = menuList111.list
          // if (!aaa) {
          //   reject(response.msg)
          // }
          // console.log(1)
          var aaa = response.data
          commit('SET_MENULIST', aaa)
          resolve({ aaa })
        }
      }).catch(error => {
        reject(error)
      })
      // var aaa = menuList111.list
      // commit('SET_MENULIST', aaa)
      // resolve({ aaa })
    })
  },
  // 部门
  getDeptList({ commit }) {
    return new Promise((resolve, reject) => {
      getAllDepts().then(res => {
        if (res?.code !== 200) {
          reject(res.msg)
        } else {
          let deptList = res.data.list
          //   console.log(deptList)
          if (deptList && deptList.length >= 1) {
            commit('SET_ORIDEPTLIST', deptList) // 未经递归处理的deptList
            const array = changeDeptList2Tree(0, deptList)
            deptList = array // 经递归处理后的deptList
            // console.log(deptList)
            commit('SET_DEPTLIST', deptList) // 经过层级处理过的deptList
            resolve({
              deptList
            })
          } else {
            reject('无部门记录')
          }
        }
      })
        .catch(error => {
          reject(error)
        })
    })
  },
  // 区域树
  getDistrinctTree({ commit }) {
    return new Promise((resolve, reject) => {
      // const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      getDistinctList(0).then(res => {
        if (res.code !== 0) {
          reject(res.msg)
        } else {
          const areaList = res.data
          // console.log(areaList)
          if (areaList && areaList.length >= 1) {
            commit('SET_AREALIST', areaList)
            resolve({ areaList })
          } else {
            reject('无区域信息')
          }
        }
      })
        .catch(error => {
          reject(error)
        })
    })
  },
  // 物流公司
  getLogisticsLists({ commit }) {
    return new Promise((resolve, reject) => {
      getLogisticsList({}).then(res => {
        if (res.code !== 0) {
          reject(res.msg)
        } else {
          const logisticsList = res.data
          // console.log(logisticsList)
          if (logisticsList && logisticsList.length >= 1) {
            commit('SET_LOGISTICSLIST', logisticsList)
            resolve({ logisticsList })
          } else {
            reject('无物流公司信息')
          }
        }
      })
        .catch(error => {
          reject(error)
        })
    })
  },
  // 用户登出
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_MENULIST', [])
      removeToken()
      resetRouter()
      dispatch('tagsView/delAllViews', null, { root: true })
      resolve()
    })
  },
  // 清除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_MENULIST', [])
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
